import store from './store'
import router, { resetRouter } from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { jumpToLogin, loadingInstance } from '@/utils/public'
import { getToken } from '@/utils/auth'
import { init } from '@/api/main'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach((to, from, next) => {
  NProgress.start()

  const hasToken = getToken() && getToken() !== 'undefined'
  if (hasToken) {
    // next()
    if (store.getters.permission_routes.length) {
      next()
    } else {
      initMenu(next, to, from)
    }
  } else {
    if (to.path === '/login') {
      next()
    } else {
      jumpToLogin()
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  // finish progress bar
  NProgress.done()
})

function initMenu(next, to, from) {
  const loading = loadingInstance()
  return init({ clientIds: 'cdtye-common-sys-client' })
    .then(async(response) => {
      const accessRoutes = await store.dispatch('permission/generateRoutes', response.data)
      resetRouter()
      router.addRoutes(accessRoutes)
      next(to.path)
      loading.close()
    }).catch(_ => {
      NProgress.done()
      loading.close()
    })
}
